package auth

import (
	"cloud-navigation/app/common/request"
	"cloud-navigation/app/common/response"
	"cloud-navigation/app/services"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

// 用户注册
func Register(c *gin.Context) {
	var form request.Register
	if !services.Request(c, &form) {
		return
	}
	// if err := c.ShouldBindJSON(&form); err != nil {
	// 	response.ValidateFail(c, request.GetErrorMsg(form, err))
	// 	return
	// }

	if user, err := services.UserService.Register(form); err != nil {
		response.BusinessFail(c, err.Error())
	} else {
		response.Success(c, user)
	}
}

// 用户退出
func Logout(c *gin.Context) {
	err := services.JwtService.JoinBlackList(c.Keys["token"].(*jwt.Token))
	if err != nil {
		response.BusinessFail(c, "退出失败")
		return
	}
	response.Success(c, nil)
}

// 用户登录
func Login(c *gin.Context) {
	var form request.Login
	if !services.Request(c, &form) {
		return
	}
	// if err := c.ShouldBindJSON(&form); err != nil {
	// 	response.ValidateFail(c, request.GetErrorMsg(form, err), gin.H{})
	// 	return
	// }

	if user, err := services.UserService.Login(form); err != nil {
		response.BusinessFail(c, err.Error())
	} else {
		tokenData, _, err := services.JwtService.CreateToken(services.AppGuardName, &user)
		if err != nil {
			response.BusinessFail(c, err.Error())
			return
		}
		response.Success(c, tokenData)
	}
}
